<template>
  <div class="app-container">
    <div class="date-picker-container">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        size="default"
        :shortcuts="shortcuts"
          value-format="YYYY-MM-DD"
        @change="handleDateChange"
        />
      <el-button type="primary" @click="fetchAllStats">刷新数据</el-button>
      </div>

    <!-- 顶部卡片统计 -->
    <el-row :gutter="20" class="card-row">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-title">就诊总人数</div>
          <div class="stat-value">{{ formatNumber(overviewStats.totalPatients || 0) }}</div>
          <div class="stat-trend" :class="overviewStats.patientTrend >= 0 ? 'up' : 'down'">
            <el-icon v-if="overviewStats.patientTrend >= 0"><ArrowUp /></el-icon>
            <el-icon v-else><ArrowDown /></el-icon>
            {{ Math.abs(overviewStats.patientTrend || 0) }}%
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-title">医嘱总数</div>
          <div class="stat-value">{{ formatNumber(overviewStats.totalOrders || 0) }}</div>
          <div class="stat-trend" :class="overviewStats.orderTrend >= 0 ? 'up' : 'down'">
            <el-icon v-if="overviewStats.orderTrend >= 0"><ArrowUp /></el-icon>
            <el-icon v-else><ArrowDown /></el-icon>
            {{ Math.abs(overviewStats.orderTrend || 0) }}%
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-title">处方总数</div>
          <div class="stat-value">{{ formatNumber(overviewStats.totalPrescriptions || 0) }}</div>
          <div class="stat-trend" :class="overviewStats.prescriptionTrend >= 0 ? 'up' : 'down'">
            <el-icon v-if="overviewStats.prescriptionTrend >= 0"><ArrowUp /></el-icon>
            <el-icon v-else><ArrowDown /></el-icon>
            {{ Math.abs(overviewStats.prescriptionTrend || 0) }}%
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-title">总收入</div>
          <div class="stat-value">¥{{ formatNumber(overviewStats.totalIncome || 0) }}</div>
          <div class="stat-trend" :class="overviewStats.incomeTrend >= 0 ? 'up' : 'down'">
            <el-icon v-if="overviewStats.incomeTrend >= 0"><ArrowUp /></el-icon>
            <el-icon v-else><ArrowDown /></el-icon>
            {{ Math.abs(overviewStats.incomeTrend || 0) }}%
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 图表统计 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>就诊趋势</span>
              <el-radio-group v-model="visitTrendType" size="small" @change="loadVisitTrend">
                <el-radio-button label="daily">日</el-radio-button>
                <el-radio-button label="weekly">周</el-radio-button>
                <el-radio-button label="monthly">月</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container" v-loading="visitChartLoading">
            <div ref="visitChartRef" class="chart"></div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>收入分析</span>
              <el-radio-group v-model="incomeChartType" size="small" @change="loadIncomeData">
                <el-radio-button label="trend">趋势图</el-radio-button>
                <el-radio-button label="category">分类</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container" v-loading="incomeChartLoading">
            <div ref="incomeChartRef" class="chart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 科室和医生统计 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>科室工作量</span>
              <el-select v-model="deptStatType" size="small" @change="loadDepartmentStats">
                <el-option label="就诊人次" value="visits" />
                <el-option label="医嘱数量" value="orders" />
                <el-option label="收入" value="income" />
              </el-select>
            </div>
          </template>
          <div class="chart-container" v-loading="deptChartLoading">
            <div ref="deptChartRef" class="chart"></div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>医生工作量</span>
              <el-select v-model="doctorStatType" size="small" @change="loadDoctorStats">
                <el-option label="就诊人次" value="visits" />
                <el-option label="医嘱数量" value="orders" />
                <el-option label="处方数量" value="prescriptions" />
              </el-select>
            </div>
          </template>
          <div class="chart-container" v-loading="doctorChartLoading">
            <div ref="doctorChartRef" class="chart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 药品使用统计 -->
    <el-row class="chart-row">
      <el-col :span="24">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>药品使用Top 10</span>
              <el-radio-group v-model="medicineStatType" size="small" @change="loadMedicineStats">
                <el-radio-button label="count">使用次数</el-radio-button>
                <el-radio-button label="amount">使用数量</el-radio-button>
                <el-radio-button label="cost">消耗金额</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container" v-loading="medicineChartLoading">
            <div ref="medicineChartRef" class="chart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import { statisticsAPI } from '@/utils/api'
import * as echarts from 'echarts/core'
import { LineChart, BarChart, PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  DataZoomComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

// 注册必要的 ECharts 组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  DataZoomComponent,
  LineChart,
  BarChart,
  PieChart,
  CanvasRenderer
])

// 日期选择相关
const dateRange = ref([])
const shortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

// 初始化日期范围为最近30天
const initDateRange = () => {
  const end = new Date()
  const start = new Date()
  start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
  dateRange.value = [formatDate(start), formatDate(end)]
}

// 格式化日期
const formatDate = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 格式化数字
const formatNumber = (num) => {
  return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
}

// 数据统计和图表类型
const visitTrendType = ref('daily')
const incomeChartType = ref('trend')
const deptStatType = ref('orders')
const doctorStatType = ref('orders')
const medicineStatType = ref('count')

// 图表引用
const visitChartRef = ref(null)
const incomeChartRef = ref(null)
const deptChartRef = ref(null)
const doctorChartRef = ref(null)
const medicineChartRef = ref(null)

// 图表实例
let visitChart = null
let incomeChart = null
let deptChart = null
let doctorChart = null
let medicineChart = null

// 加载状态
const visitChartLoading = ref(false)
const incomeChartLoading = ref(false)
const deptChartLoading = ref(false)
const doctorChartLoading = ref(false)
const medicineChartLoading = ref(false)

// 统计数据
const overviewStats = reactive({
  totalPatients: 0,
  totalOrders: 0,
  totalPrescriptions: 0,
  totalIncome: 0,
  patientTrend: 0,
  orderTrend: 0,
  prescriptionTrend: 0,
  incomeTrend: 0
})

// 日期变化处理
const handleDateChange = () => {
  fetchAllStats()
}

// 获取所有统计数据
const fetchAllStats = () => {
  fetchOverviewStats()
  // 直接调用加载各类统计数据的函数
  loadVisitTrend()
  loadIncomeData()
  loadDepartmentStats()
  loadDoctorStats()
  loadMedicineStats()
}

// 获取概览统计数据
const fetchOverviewStats = async () => {
  try {
    // 设置加载状态
    visitChartLoading.value = true
    incomeChartLoading.value = true
    deptChartLoading.value = true
    doctorChartLoading.value = true
    medicineChartLoading.value = true
    
    // 使用静态模拟数据
    
    // 1. 就诊趋势数据
    const visitMockData = {
      total: 5823,
      statistics: Array.from({ length: 30 }, (_, i) => ({
        date: formatDate(new Date(Date.now() - (29 - i) * 24 * 3600 * 1000)),
        count: Math.floor(Math.random() * 50) + 150,
        departmentCount: 8
      }))
    }
    overviewStats.totalPatients = visitMockData.total
    overviewStats.patientTrend = 15
    renderVisitChart({ statistics: visitMockData.statistics })
    visitChartLoading.value = false
    
    // 2. 收入趋势数据
    const incomeMockData = {
      total: { amount: 283650, count: 4120 },
      statistics: Array.from({ length: 30 }, (_, i) => ({
        date: formatDate(new Date(Date.now() - (29 - i) * 24 * 3600 * 1000)),
        totalAmount: Math.floor(Math.random() * 5000) + 8000,
        count: Math.floor(Math.random() * 20) + 100
      }))
    }
    overviewStats.totalIncome = incomeMockData.total.amount
    overviewStats.incomeTrend = 12
    renderIncomeTrendChart({ statistics: incomeMockData.statistics })
    incomeChartLoading.value = false
    
    // 3. 处方和医嘱数据
    overviewStats.totalPrescriptions = 4620
    overviewStats.totalOrders = 6930
    overviewStats.prescriptionTrend = 8
    overviewStats.orderTrend = 11
    
    // 4. 科室统计数据
    const deptMockData = {
      departments: [
        { departmentName: '内科', appointmentCount: 1250, prescriptionCount: 980, totalAmount: 98500 },
        { departmentName: '外科', appointmentCount: 890, prescriptionCount: 750, totalAmount: 75800 },
        { departmentName: '儿科', appointmentCount: 760, prescriptionCount: 650, totalAmount: 55600 },
        { departmentName: '妇产科', appointmentCount: 680, prescriptionCount: 580, totalAmount: 62300 },
        { departmentName: '骨科', appointmentCount: 560, prescriptionCount: 430, totalAmount: 48900 },
        { departmentName: '眼科', appointmentCount: 480, prescriptionCount: 360, totalAmount: 42000 },
        { departmentName: '口腔科', appointmentCount: 420, prescriptionCount: 350, totalAmount: 38500 },
        { departmentName: '皮肤科', appointmentCount: 380, prescriptionCount: 290, totalAmount: 32400 }
      ]
    }
    renderDepartmentChart(deptMockData, deptStatType.value === 'visits' ? 'appointmentCount' : 
                       (deptStatType.value === 'orders' ? 'prescriptionCount' : 'totalAmount'))
    deptChartLoading.value = false
    
    // 5. 医生统计数据
    const doctorMockData = {
      total: {
        totalDoctors: 8,
        totalAppointments: 65,
        totalPrescriptions: 48,
        totalRecords: 36,
        totalAmount: 45280.0
      },
      doctors: [
        {
          doctorId: "682c66259c685dc25de0d5cd",
          departmentId: "682c55b57d196017f623bcf0",
          appointmentCount: 12,
          prescriptionCount: 10,
          recordCount: 8,
          totalAmount: 12080.0,
          title: "副主任医师",
          doctorName: "李医生",
          departmentName: "内科",
          efficiency: 453.33
        },
        {
          doctorId: "682d2f6990ac03e712823f02",
          departmentId: "682c55b57d196017f623bcf0",
          appointmentCount: 9,
          prescriptionCount: 7,
          recordCount: 5,
          totalAmount: 7800.0,
          title: "副主任医师",
          doctorName: "王主任",
          departmentName: "内科",
          efficiency: 387.5
        },
        {
          doctorId: "682d2f0a90ac03e712823f01",
          departmentId: "682c55bb7d196017f623bcf1",
          appointmentCount: 11,
          prescriptionCount: 9,
          recordCount: 7,
          totalAmount: 9850.0,
          title: "主治医师",
          doctorName: "张医生",
          departmentName: "外科",
          efficiency: 422.14
        },
        {
          doctorId: "682d2f8f90ac03e712823f03",
          departmentId: "682c55bb7d196017f623bcf1",
          appointmentCount: 8,
          prescriptionCount: 6,
          recordCount: 4,
          totalAmount: 6200.0,
          title: "住院医师",
          doctorName: "刘医生",
          departmentName: "外科",
          efficiency: 310.0
        },
        {
          doctorId: "682d2faf90ac03e712823f04",
          departmentId: "682c55c37d196017f623bcf2",
          appointmentCount: 7,
          prescriptionCount: 5,
          recordCount: 4,
          totalAmount: 4350.0,
          title: "主任医师",
          doctorName: "赵专家",
          departmentName: "儿科",
          efficiency: 362.5
        },
        {
          doctorId: "682d2fce90ac03e712823f05",
          departmentId: "682c55c37d196017f623bcf2",
          appointmentCount: 6,
          prescriptionCount: 4,
          recordCount: 3,
          totalAmount: 3200.0,
          title: "主治医师",
          doctorName: "钱医生",
          departmentName: "儿科",
          efficiency: 266.67
        },
        {
          doctorId: "682d2fed90ac03e712823f06",
          departmentId: "682c55cc7d196017f623bcf3",
          appointmentCount: 5,
          prescriptionCount: 4,
          recordCount: 3,
          totalAmount: 2800.0,
          title: "副主任医师",
          doctorName: "孙医生",
          departmentName: "妇产科",
          efficiency: 233.33
        },
        {
          doctorId: "682d300b90ac03e712823f07",
          departmentId: "682c55cc7d196017f623bcf3",
          appointmentCount: 4,
          prescriptionCount: 3,
          recordCount: 2,
          totalAmount: 1800.0,
          title: "住院医师",
          doctorName: "周医生",
          departmentName: "妇产科",
          efficiency: 180.0
        }
      ]
    }
    renderDoctorChart(doctorMockData, doctorStatType.value)
    doctorChartLoading.value = false
    
    // 6. 药品使用统计数据
    const medicineMockData = {
      medicines: [
        { medicineName: "阿莫西林胶囊", useCount: 186, totalAmount: 372, totalCost: 5580.0 },
        { medicineName: "布洛芬片", useCount: 165, totalAmount: 495, totalCost: 4950.0 },
        { medicineName: "头孢克肟片", useCount: 145, totalAmount: 290, totalCost: 8700.0 },
        { medicineName: "奥美拉唑肠溶胶囊", useCount: 132, totalAmount: 264, totalCost: 6600.0 },
        { medicineName: "复方感冒灵颗粒", useCount: 128, totalAmount: 384, totalCost: 3840.0 },
        { medicineName: "板蓝根颗粒", useCount: 112, totalAmount: 336, totalCost: 3360.0 },
        { medicineName: "氨咖黄敏胶囊", useCount: 102, totalAmount: 306, totalCost: 3060.0 },
        { medicineName: "葡萄糖注射液", useCount: 95, totalAmount: 95, totalCost: 1900.0 },
        { medicineName: "维生素C片", useCount: 88, totalAmount: 264, totalCost: 2640.0 },
        { medicineName: "藿香正气水", useCount: 82, totalAmount: 82, totalCost: 1640.0 }
      ]
    }
    renderMedicineChart(medicineMockData, medicineStatType.value)
    medicineChartLoading.value = false
    
  } catch (error) {
    console.error('获取概览统计数据失败:', error)
  } finally {
    // 结束加载状态
    visitChartLoading.value = false
    incomeChartLoading.value = false
    deptChartLoading.value = false
    doctorChartLoading.value = false
    medicineChartLoading.value = false
  }
}

// 加载就诊趋势数据
const loadVisitTrend = async () => {
  try {
    visitChartLoading.value = true
    
    // 生成模拟数据
    const dates = []
    const visitCounts = []
    const newPatients = []
    const returnPatients = []
    
    // 根据选择的时间粒度生成数据
    if (visitTrendType.value === 'daily') {
      // 生成30天的数据
      for (let i = 0; i < 30; i++) {
        const date = new Date()
        date.setDate(date.getDate() - (29 - i))
        dates.push(formatDate(date))
        
        const total = Math.floor(Math.random() * 50) + 100
        const newCount = Math.floor(total * (0.3 + Math.random() * 0.2))
        visitCounts.push(total)
        newPatients.push(newCount)
        returnPatients.push(total - newCount)
      }
    } else if (visitTrendType.value === 'weekly') {
      // 生成12周的数据
      for (let i = 0; i < 12; i++) {
        const date = new Date()
        date.setDate(date.getDate() - (11 - i) * 7)
        dates.push(`第${i + 1}周`)
        
        const total = Math.floor(Math.random() * 300) + 600
        const newCount = Math.floor(total * (0.3 + Math.random() * 0.2))
        visitCounts.push(total)
        newPatients.push(newCount)
        returnPatients.push(total - newCount)
      }
    } else {
      // 生成12个月的数据
      for (let i = 0; i < 12; i++) {
        const date = new Date()
        date.setMonth(date.getMonth() - (11 - i))
        const monthNames = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']
        dates.push(monthNames[date.getMonth()])
        
        const total = Math.floor(Math.random() * 1000) + 2000
        const newCount = Math.floor(total * (0.3 + Math.random() * 0.2))
        visitCounts.push(total)
        newPatients.push(newCount)
        returnPatients.push(total - newCount)
      }
    }

    // 渲染图表
    renderVisitChart({
      dates,
      visitCounts,
      newPatients,
      returnPatients
    })
  } catch (error) {
    console.error('加载就诊趋势数据失败:', error)
  } finally {
    visitChartLoading.value = false
  }
}

// 渲染就诊趋势图表
const renderVisitChart = (data) => {
  if (!visitChart) {
    visitChart = echarts.init(visitChartRef.value)
  }
  
  const option = {
    title: {
      text: '就诊趋势统计',
      left: 'center',
      textStyle: {
        fontSize: 16
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['总就诊量', '新患者', '复诊患者'],
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: data.dates || data.statistics.map(item => item.date),
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '就诊人次'
    },
    series: [
      {
        name: '总就诊量',
        type: 'line',
        smooth: true,
        data: data.visitCounts || data.statistics.map(item => item.count),
        itemStyle: {
          color: '#409EFF'
        },
        lineStyle: {
          width: 3
        },
        symbolSize: 8
      },
      {
        name: '新患者',
        type: 'bar',
        stack: 'total',
        data: data.newPatients || data.statistics.map(item => Math.floor(item.count * 0.35)),
        itemStyle: {
          color: '#67C23A'
        }
      },
      {
        name: '复诊患者',
        type: 'bar',
        stack: 'total',
        data: data.returnPatients || data.statistics.map(item => Math.floor(item.count * 0.65)),
        itemStyle: {
          color: '#E6A23C'
        }
      }
    ]
  }
  
  visitChart.setOption(option)
  window.addEventListener('resize', () => {
    visitChart && visitChart.resize()
  })
}

// 加载收入数据
const loadIncomeData = async () => {
  try {
    incomeChartLoading.value = true
    
    if (incomeChartType.value === 'trend') {
      // 生成收入趋势数据
      const dates = []
      const incomeData = []
      
      // 根据日期范围生成30天的数据
      for (let i = 0; i < 30; i++) {
        const date = new Date()
        date.setDate(date.getDate() - (29 - i))
        dates.push(formatDate(date))
        incomeData.push(Math.floor(Math.random() * 5000) + 8000)
      }
      
      renderIncomeTrendChart({
        dates,
        incomeData
      })
    } else {
      // 生成收入分类数据
      const categoryData = [
        { name: '挂号费', value: 45800, percentage: 16.15 },
        { name: '药品费', value: 112500, percentage: 39.66 },
        { name: '检查费', value: 78300, percentage: 27.60 },
        { name: '治疗费', value: 32000, percentage: 11.28 },
        { name: '其他', value: 15050, percentage: 5.31 }
      ]
      
      renderIncomeCategoryChart(categoryData)
    }
  } catch (error) {
    console.error('加载收入数据失败:', error)
  } finally {
    incomeChartLoading.value = false
  }
}

// 渲染收入趋势图表
const renderIncomeTrendChart = (data) => {
  if (!incomeChart) {
    incomeChart = echarts.init(incomeChartRef.value)
  }
  
  const option = {
    title: {
      text: '收入趋势统计',
      left: 'center',
      textStyle: {
        fontSize: 16
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'line'
      },
      formatter: '{b}<br />收入: ¥{c}'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: data.dates || data.statistics.map(item => item.date),
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '收入金额',
      axisLabel: {
        formatter: '¥{value}'
      }
    },
    series: [
      {
        name: '收入',
        type: 'line',
        smooth: true,
        data: data.incomeData || data.statistics.map(item => item.totalAmount),
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(128, 0, 128, 0.8)' },
              { offset: 1, color: 'rgba(128, 0, 128, 0.1)' }
            ]
          }
        },
        itemStyle: {
          color: 'purple'
        },
        lineStyle: {
          width: 3
        },
        symbolSize: 8
      }
    ]
  }
  
  incomeChart.setOption(option)
  window.addEventListener('resize', () => {
    incomeChart && incomeChart.resize()
  })
}

// 渲染收入分类图表
const renderIncomeCategoryChart = (data) => {
  if (!incomeChart) {
    incomeChart = echarts.init(incomeChartRef.value)
  }
  
  const option = {
    title: {
      text: '收入分类统计',
      left: 'center',
      textStyle: {
        fontSize: 16
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: ¥{c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: data.map(item => item.name)
    },
    series: [
      {
        name: '收入分类',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['40%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: '{b}: {c} ({d}%)'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        data: data.map(item => ({
          name: item.name,
          value: item.value
        })),
        color: ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399']
      }
    ]
  }
  
  incomeChart.setOption(option)
  window.addEventListener('resize', () => {
    incomeChart && incomeChart.resize()
  })
}

// 使用静态数据加载科室统计
const loadDepartmentStats = async () => {
  try {
    deptChartLoading.value = true
    
    // 使用模拟数据
    const deptData = [
      { name: '内科', visits: 1250, orders: 980, income: 98500 },
      { name: '外科', visits: 890, orders: 750, income: 75800 },
      { name: '儿科', visits: 760, orders: 650, income: 55600 },
      { name: '妇产科', visits: 680, orders: 580, income: 62300 },
      { name: '骨科', visits: 560, orders: 430, income: 48900 },
      { name: '眼科', visits: 480, orders: 360, income: 42000 },
      { name: '口腔科', visits: 420, orders: 350, income: 38500 },
      { name: '皮肤科', visits: 380, orders: 290, income: 32400 }
    ]
    
    renderDepartmentChart(deptData, deptStatType.value)
  } catch (error) {
    console.error('加载科室统计数据失败:', error)
  } finally {
    deptChartLoading.value = false
  }
}

// 渲染科室统计图表
const renderDepartmentChart = (data, type) => {
  if (!deptChart) {
    deptChart = echarts.init(deptChartRef.value)
  }
  
  let statData
  let unitName
  
  if (typeof data.departments !== 'undefined') {
    // 适配旧数据结构
    data = data.departments.map(dept => ({
      name: dept.departmentName,
      visits: dept.appointmentCount,
      orders: dept.prescriptionCount,
      income: dept.totalAmount
    }))
  }
  
  if (type === 'visits') {
    statData = data.map(item => ({ name: item.name, value: item.visits }))
    unitName = '就诊人次'
  } else if (type === 'orders') {
    statData = data.map(item => ({ name: item.name, value: item.orders }))
    unitName = '医嘱数量'
  } else {
    statData = data.map(item => ({ name: item.name, value: item.income }))
    unitName = '收入金额'
  }
  
  // 按值排序
  statData.sort((a, b) => b.value - a.value)
  
  const option = {
    title: {
      text: '科室工作量统计',
      left: 'center',
      textStyle: {
        fontSize: 16
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: (params) => {
        const param = params[0]
        return `${param.name}<br />${unitName}: ${type === 'income' ? '¥' : ''}${param.value}`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      name: unitName,
      axisLabel: {
        formatter: type === 'income' ? '¥{value}' : '{value}'
      }
    },
    yAxis: {
      type: 'category',
      data: statData.map(item => item.name),
      axisLabel: {
        interval: 0
      }
    },
    series: [
      {
        name: unitName,
        type: 'bar',
        data: statData.map(item => item.value),
        itemStyle: {
          color: function(params) {
            const colorList = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399', '#8e6cef', '#3cb371', '#60acfc']
            return colorList[params.dataIndex % colorList.length]
          },
          borderRadius: [0, 4, 4, 0]
        },
        label: {
          show: true,
          position: 'right',
          formatter: type === 'income' ? '¥{c}' : '{c}'
        }
      }
    ]
  }
  
  deptChart.setOption(option)
  window.addEventListener('resize', () => {
    deptChart && deptChart.resize()
  })
}

// 加载医生统计数据
const loadDoctorStats = async () => {
  try {
    doctorChartLoading.value = true
    
    // 使用模拟数据
    const doctorData = [
      {
        name: '李医生',
        department: '内科',
        title: '副主任医师',
        visits: 132,
        orders: 108,
        prescriptions: 98
      },
      {
        name: '王主任',
        department: '内科',
        title: '主任医师',
        visits: 118,
        orders: 93,
        prescriptions: 85
      },
      {
        name: '张医生',
        department: '外科',
        title: '主治医师',
        visits: 105,
        orders: 86,
        prescriptions: 76
      },
      {
        name: '刘医生',
        department: '外科',
        title: '住院医师',
        visits: 92,
        orders: 73,
        prescriptions: 64
      },
      {
        name: '赵专家',
        department: '儿科',
        title: '主任医师',
        visits: 85,
        orders: 68,
        prescriptions: 60
      },
      {
        name: '钱医生',
        department: '儿科',
        title: '主治医师',
        visits: 78,
        orders: 62,
        prescriptions: 54
      },
      {
        name: '孙医生',
        department: '妇产科',
        title: '副主任医师',
        visits: 65,
        orders: 52,
        prescriptions: 46
      },
      {
        name: '周医生',
        department: '妇产科',
        title: '住院医师',
        visits: 59,
        orders: 47,
        prescriptions: 41
      }
    ]
    
    renderDoctorChart(doctorData, doctorStatType.value)
  } catch (error) {
    console.error('加载医生统计数据失败:', error)
  } finally {
    doctorChartLoading.value = false
  }
}

// 渲染医生统计图表
const renderDoctorChart = (data, type) => {
  if (!doctorChart) {
    doctorChart = echarts.init(doctorChartRef.value)
  }
  
  let statData
  let unitName
  
  if (typeof data.doctors !== 'undefined') {
    // 适配旧数据结构
    data = data.doctors.map(doc => ({
      name: doc.doctorName,
      department: doc.departmentName,
      title: doc.title,
      visits: doc.appointmentCount,
      orders: doc.prescriptionCount,
      prescriptions: doc.prescriptionCount
    }))
  }
  
  if (type === 'visits') {
    statData = data.map(item => ({ 
      name: item.name, 
      value: item.visits,
      department: item.department,
      title: item.title
    }))
    unitName = '就诊人次'
  } else if (type === 'orders') {
    statData = data.map(item => ({ 
      name: item.name, 
      value: item.orders,
      department: item.department,
      title: item.title
    }))
    unitName = '医嘱数量'
  } else {
    statData = data.map(item => ({ 
      name: item.name, 
      value: item.prescriptions,
      department: item.department,
      title: item.title
    }))
    unitName = '处方数量'
  }
  
  // 按值排序
  statData.sort((a, b) => b.value - a.value)
  // 取前10名
  statData = statData.slice(0, 10)
  
  const option = {
    title: {
      text: '医生工作量统计',
      left: 'center',
      textStyle: {
        fontSize: 16
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: (params) => {
        const param = params[0]
        const item = statData[param.dataIndex]
        return `${item.name}（${item.department} - ${item.title}）<br />${unitName}: ${param.value}`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      name: unitName
    },
    yAxis: {
      type: 'category',
      data: statData.map(item => item.name),
      axisLabel: {
        interval: 0
      }
    },
    series: [
      {
        name: unitName,
        type: 'bar',
        data: statData.map(item => item.value),
        itemStyle: {
          color: function(params) {
            const colorList = ['#F56C6C', '#E6A23C', '#409EFF', '#67C23A', '#909399', '#8e6cef', '#3cb371', '#60acfc']
            return colorList[params.dataIndex % colorList.length]
          },
          borderRadius: [4, 4, 0, 0]
        },
        label: {
          show: true,
          position: 'top',
          formatter: '{c}'
        }
      }
    ]
  }
  
  doctorChart.setOption(option)
  window.addEventListener('resize', () => {
    doctorChart && doctorChart.resize()
  })
}

// 加载药品使用统计数据
const loadMedicineStats = async () => {
  try {
    medicineChartLoading.value = true
    
    // 使用模拟数据
    const medicineData = [
      { name: '阿莫西林胶囊', count: 186, amount: 372, cost: 5580 },
      { name: '布洛芬片', count: 165, amount: 495, cost: 4950 },
      { name: '头孢克肟片', count: 145, amount: 290, cost: 8700 },
      { name: '奥美拉唑肠溶胶囊', count: 132, amount: 264, cost: 6600 },
      { name: '复方感冒灵颗粒', count: 128, amount: 384, cost: 3840 },
      { name: '板蓝根颗粒', count: 112, amount: 336, cost: 3360 },
      { name: '氨咖黄敏胶囊', count: 102, amount: 306, cost: 3060 },
      { name: '葡萄糖注射液', count: 95, amount: 95, cost: 1900 },
      { name: '维生素C片', count: 88, amount: 264, cost: 2640 },
      { name: '藿香正气水', count: 82, amount: 82, cost: 1640 }
    ]
    
    renderMedicineChart(medicineData, medicineStatType.value)
  } catch (error) {
    console.error('加载药品使用统计数据失败:', error)
  } finally {
    medicineChartLoading.value = false
  }
}

// 渲染药品使用统计图表
const renderMedicineChart = (data, type) => {
  if (!medicineChart) {
    medicineChart = echarts.init(medicineChartRef.value)
  }
  
  let statData
  let unitName
  
  if (typeof data.medicines !== 'undefined') {
    // 适配旧数据结构
    data = data.medicines.map(med => ({
      name: med.medicineName,
      count: med.useCount,
      amount: med.totalAmount,
      cost: med.totalCost
    }))
  }
  
  if (type === 'count') {
    statData = data.map(item => ({ 
      name: item.name, 
      value: item.count
    }))
    unitName = '使用次数'
  } else if (type === 'amount') {
    statData = data.map(item => ({ 
      name: item.name, 
      value: item.amount
    }))
    unitName = '使用数量'
  } else {
    statData = data.map(item => ({ 
      name: item.name, 
      value: item.cost
    }))
    unitName = '消耗金额'
  }
  
  // 按值排序
  statData.sort((a, b) => b.value - a.value)
  // 取前10名
  statData = statData.slice(0, 10)
  
  const option = {
    title: {
      text: '药品使用TOP 10',
      left: 'center',
      textStyle: {
        fontSize: 16
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: (params) => {
        const param = params[0]
        return `${param.name}<br />${unitName}: ${type === 'cost' ? '¥' : ''}${param.value}`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: statData.map(item => {
        let name = item.name
        if (name.length > 8) {
          name = name.substring(0, 8) + '...'
        }
        return name
      }),
      axisLabel: {
        interval: 0,
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: unitName,
      axisLabel: {
        formatter: type === 'cost' ? '¥{value}' : '{value}'
      }
    },
    series: [
      {
        name: unitName,
        type: 'bar',
        data: statData.map(item => item.value),
        itemStyle: {
          color: function(params) {
            const colorList = ['#3CB371', '#60ACFC', '#8E6CEF', '#F56C6C', '#E6A23C', '#409EFF', '#67C23A', '#909399']
            return colorList[params.dataIndex % colorList.length]
          },
          borderRadius: [4, 4, 0, 0]
        },
        label: {
          show: true,
          position: 'top',
          formatter: '{c}'
        }
      }
    ]
  }
  
  medicineChart.setOption(option)
  window.addEventListener('resize', () => {
    medicineChart && medicineChart.resize()
  })
}

// 初始化所有图表
const initCharts = () => {
  nextTick(() => {
    if (visitChartRef.value) {
      visitChart = echarts.init(visitChartRef.value)
    }
    if (incomeChartRef.value) {
      incomeChart = echarts.init(incomeChartRef.value)
    }
    if (deptChartRef.value) {
      deptChart = echarts.init(deptChartRef.value)
    }
    if (doctorChartRef.value) {
      doctorChart = echarts.init(doctorChartRef.value)
    }
    if (medicineChartRef.value) {
      medicineChart = echarts.init(medicineChartRef.value)
    }
  })
}

// 生命周期钩子
onMounted(() => {
  initDateRange()
  initCharts()
  // 立即获取数据，不等待用户操作
  nextTick(() => {
    fetchAllStats()
  })
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.date-picker-container {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  gap: 15px;
}

.card-row {
  margin-bottom: 20px;
}

.chart-row {
  margin-bottom: 20px;
}

.stat-card {
  height: 120px;
  text-align: center;
  display: flex;
  flex-direction: column;
  justify-content: center;
  background-image: linear-gradient(to right, rgba(240, 248, 255, 0.6), rgba(240, 248, 255, 0.2));
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s, box-shadow 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.stat-title {
  color: #606266;
  font-size: 14px;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 8px;
}

.stat-trend {
  font-size: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.stat-trend.up {
  color: #67C23A;
}

.stat-trend.down {
  color: #F56C6C;
}

.chart-card {
  margin-bottom: 20px;
  height: 400px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border-radius: 8px;
  transition: box-shadow 0.3s;
}

.chart-card:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 320px;
}

.chart {
  height: 100%;
  width: 100%;
}
</style> 